import Vue from 'vue'
import VueRouter from 'vue-router'
import Admin from '@views/Admin'
import Login from '@views/Login'
import Welcome from '@views/Welcome'
import Orders from '@views/Orders'
import Categories from '@views/Categories'
import Goods from '@views/Goods'
import Params from '@views/Params'
import Reports from '@views/Reports'
import Rights from '@views/Rights'
import Roles from '@views/Roles'
import Users from '@views/Users'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/admin'
  },
  {
    path: '/admin',
    name: 'admin',
    component: Admin,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: Welcome
      },
      {
        path: '/orders',
        name: 'orders',
        component: Orders
      },
      {
        path: '/categories',
        name: 'categories',
        component: Categories
      },
      {
        path: '/goods',
        name: 'goods',
        component: Goods
      },
      {
        path: '/params',
        name: 'params',
        component: Params
      },
      {
        path: '/reports',
        name: 'reports',
        component: Reports
      },
      {
        path: '/rights',
        name: 'rights',
        component: Rights
      },
      {
        path: '/roles',
        name: 'roles',
        component: Roles
      },
      {
        path: '/users',
        name: 'users',
        component: Users
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 配置路由登录权限
router.beforeEach((to, from, next) => {
  // 判断目标路由是否是 /login
  const token = window.sessionStorage.getItem('token')
  if (to.fullPath === '/login') {
    // 如果是，放行
    next()
  } else {
    // 如果不是，判断是否已登录
    if (!token) {
      // 如果未登录，重定向到 登录页
      next({
        name: 'login',
        params: {
          from: to.fullPath
        }
      })
    } else {
      // 表示已登录 ， 放行
      next()
    }
  }
})
export default router
